define([
  'require'
], function () {
  'use strict';
  var option = {
    detectBounds: false,// 是否检测边界
    moveableArea: null,// 边界矩形，PIXI.Rectangle
  };
  var $option;

  function onDragStart (e) {
    this.dragData = e.data;
    this.dragging = true;
  }

  function onDragMove (e) {
    if (this.dragging) {
      var newPos = this.dragData.getLocalPosition(this.parent);


      var detectBounds = $option.detectBounds || option.detectBounds,
        moveableArea = $option.moveableArea || option.moveableArea;
      
      if (detectBounds && moveableArea) {
        if (moveableArea.contains(newPos.x, this.position.y)) {
          this.position.x = newPos.x;
        } 
        if (moveableArea.contains(this.position.x, newPos.y)) {
          this.position.y = newPos.y;
        }
      } else {
        this.position.x = newPos.x;
        this.position.y = newPos.y;
      }

      if (!detectBounds || !moveableArea || moveableArea.contains(newPos.x, newPos.y)) {
        this.position.x = newPos.x;
        this.position.y = newPos.y;
      }

    }
  }

  function onDragEnd (e) {
    this.dragData = null;
    this.dragging = false;
  }

  function applyDrag (sprite, _option) {
    option.sprite = sprite;
    $option = _option;
    sprite.on('pointerdown', onDragStart)
      .on('pointermove', onDragMove)
      .on('pointerup', onDragEnd)
      .on('pointerupoutside', onDragEnd);
  }

  return {
    onDragStart: onDragStart,
    onDragMove: onDragMove,
    onDragEnd: onDragEnd,

    applyDrag: applyDrag
  };

});